package xyz.sundy.sftp.controller;

import xyz.sundy.sftp.client.SftpConnectionPool;
import xyz.sundy.sftp.vo.RequestVo;
import xyz.sundy.sftp.vo.SftpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author Sundy
 * @since 2025/7/2 17:06
 */
@Slf4j
@RestController
@RequestMapping(produces= MediaType.APPLICATION_JSON_VALUE)
public class SftpController {

    @Resource(name = "sftpConnectionPool")
    private SftpConnectionPool sftpConnection;

    @RequestMapping(path = "/sftp_put_file", method = {RequestMethod.POST})
    public ResponseEntity<String> putFile(@RequestBody RequestVo requestVo) {
        try {
            sftpConnection.putFile(requestVo.getSftp_name(), requestVo.getLocal_file(), requestVo.getRemote_file());
        } catch (Exception e) {
            log.error("上传文件异常", e);
            return ResponseEntity.ok(SftpResult.isFail(e.getMessage()));
        }
        return ResponseEntity.ok(SftpResult.isSuccess());
    }

    @RequestMapping(path = "/sftp_get_file", method = {RequestMethod.POST})
    public ResponseEntity<String> getFile(@RequestBody RequestVo requestVo) {
        try {
            sftpConnection.getFile(requestVo.getSftp_name(), requestVo.getLocal_file(), requestVo.getRemote_file());
        } catch (Exception e) {
            log.error("下载文件异常", e);
            return ResponseEntity.ok(SftpResult.isFail(e.getMessage()));
        }
        return ResponseEntity.ok(SftpResult.isSuccess());
    }

    @RequestMapping(path = "/reset_pool", method = {RequestMethod.POST})
    public ResponseEntity<String> restPool(@RequestBody RequestVo requestVo) {
        try {
            sftpConnection.resetSftpPool(requestVo.getSftp_name());
        } catch (Exception e) {
            log.error("重制连接池异常", e);
            return ResponseEntity.ok(SftpResult.isFail(e.getMessage()));
        }
        return ResponseEntity.ok(SftpResult.isSuccess());
    }
}